<template>
  <canvas v-if="$app.appType === 'mobile'"
    :width="width || 300"
    :height="height || 300"
    @touchstart="startPaint"
    @touchmove="paint"
    @touchend="endPaint">
  </canvas>

  <canvas v-else
    :width="width || 300"
    :height="height || 300"
    @mousedown="startPaint"
    @mousemove="paint"
    @mouseup="endPaint">
  </canvas>
</template>

<script>

export default {
  name: 'tw-paint',

  props: {
    // 画板宽度
    width: Number,

    // 画析高度
    height: Number,

    // 画线颜色
    lineColor: String,

    // 线宽
    lineWidth: {
      type: Number,
      default: 1
    },

    // 上传接口地址
    action: String
  },

  data() {
    return {
      canvas: null,
      ctx: null,
      enable: false
    }
  },

  methods: {
    init () {
      this.canvas = this.$el
      this.ctx = this.canvas.getContext('2d')
    },

    /**
    * 功能: 开始绘制
    * @param {Event} e 事件对象
    */
    startPaint (e) {
      let x = e.pageX
      let y = e.pageY

      if (this.$app.appType === 'mobile') {
        x = e.touches[0].clientX
        y = e.touches[0].clientY
      }

      this.ctx.beginPath()
      this.ctx.moveTo(x, y)
      this.ctx.strokeStyle = this.lineColor
      this.ctx.lineWidth = this.lineWidth
      this.enable = true
    },

    /**
    * 功能: 移动事件触发时，连接触发时的坐标点
    * @param {Event} e 事件对象
    */
    paint (e) {
      if (this.enable) {
        let x = e.pageX
        let y = e.pageY

        if (this.$app.appType === 'mobile') {
          x = e.touches[0].clientX
          y = e.touches[0].clientY
        }

        this.ctx.lineTo(x, y)
        this.ctx.stroke()
      }
    },

    /**
    * 功能: 结束绘制
    * @param {Event} e 事件对象
    */
    endPaint () {
      this.enable = false
    },

    /**
    * 功能: 清除画板
    * @param {Event} e 事件对象
    */
    clear () {
      this.ctx.clearRect(0, 0, this.w, this.h)
    },

    /**
    * 功能: 上传画板图片
    * @param {Event} e 事件对象
    */
    upload () {
      if (this.action) {
        this.canvas.toBlob((data) => {
          const formData = new FormData()
          // formData.append(key, value)

          const file = new File([data], this.$ui.uuid(), {
            type: 'image/png'
          })

          formData.append('file', file)

          const axiosOption = {
            method: 'post',
            url: this.action,
            data: formData,

            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }

          this.$axios(axiosOption).then(res => {
            // 上传成功逻辑
          }).catch(e => {
            // 上传失败逻辑
          })
        })
      }
    }
  },

  mounted () {
    window.aaa = this
    this.init()
  },

  created () {
    this.$app = { appType: 'mobile' }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
